package com.sky.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.result.PageResult;
import com.sky.config.JwtProperties;
import com.sky.admin.entity.dto.EmployeeLoginDTO;
import com.sky.admin.entity.dto.EmployeePageQueryDTO;
import com.sky.admin.entity.dto.PasswordEditDTO;
import com.sky.admin.entity.po.Employee;
import com.sky.admin.entity.vo.EmployeeLoginVO;
import com.sky.admin.mapper.EmployeeMapper;
import com.sky.admin.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-03
 */
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    private final EmployeeMapper employeeMapper;
    private final JwtTool jwtTool;
    private final JwtProperties jwtProperties;
    private final PasswordEncoder passwordEncoder;

    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        // 1、根据用户名查询数据库中的记录
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",employeeLoginDTO.getUsername());
        Employee employee = employeeMapper.selectOne(queryWrapper);

        // 2、处理各种情况（用户名不存在，密码错误，账号被冻结）
        // 2.1、用户名不存在
        if (employee == null)
            throw new AccountNotFoundException("用户不存在");
        // 2.2 密码错误
        String password = DigestUtils.md5DigestAsHex(String.valueOf(employeeLoginDTO.getPassword()).getBytes());
        if (!password.equals(employee.getPassword()))
            throw new PasswordErrorException("密码错误");
        // 2.3 账号冻结
        if (employee.getStatus() == StatusConstant.DISABLE)
            throw new AccountLockedException("账号已冻结");

        // 3、拷贝对象
        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        BeanUtil.copyProperties(employee,employeeLoginVO);

        // 4、生成JWT
        String token = jwtTool.createToken(employeeLoginVO.getId(), jwtProperties.getTokenTTL());
        employeeLoginVO.setToken(token);

        return employeeLoginVO;
    }

    /*
    * 启动和禁用员工账号
    * */
    @Override
    public void updateStatus(Integer status, Long id) {

        // 1、方式1
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();

        employeeMapper.updateById(employee);

        // 2、方式2
        /*UpdateWrapper<Employee> employeeUpdateWrapper = new UpdateWrapper<>();
        employeeUpdateWrapper.eq("id",id).set("status",status);
        update(employeeUpdateWrapper);*/
    }

    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());

        // 1、获取对应的密码并判断
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        // TODO 启动网关后改变此处
        queryWrapper.eq("id", BaseContext.getCurrentId() /*passwordEditDTO.getEmpId()*/)
                .eq("password",oldPassword);
        Employee employee = getOne(queryWrapper);

        if (employee == null)
            throw new PasswordErrorException("密码错误");

        // 2、修改密码
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",passwordEditDTO.getEmpId())
                .set("password",newPassword);
        update(updateWrapper);
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        int page = employeePageQueryDTO.getPage() == 0? 1:employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize() == 0? 10:employeePageQueryDTO.getPageSize();
        IPage<Employee> employeePage = new Page<>(page,pageSize);

        if (!StrUtil.isBlank(employeePageQueryDTO.getName())){
            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name",employeePageQueryDTO.getName());
            employeePage = page(employeePage,queryWrapper);
        } else {
            employeePage = page(employeePage);
        }


        return new PageResult(employeePage.getTotal(), employeePage.getRecords());
    }
}
